package com.puzzletest.net;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.UnknownHostException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.HttpHostConnectException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.net.ParseException;
import android.util.Log;

import com.puzzletest.bean.General;

public class ApiRequset {
	static String TAG = "ApiRequset";

	public static int ERRO_CODE_UNKNOWHOST = -1;
	public static int ERRO_CODE_UNSORPTENCODE = -11;
	public static int ERRO_CODE_CLIENTPROCOTOL = -12;
	public static int ERRO_CODE_IO = -13;
	public static int ERRO_CODE_UNKNOW = -14;

	/**
	 * socket,connect time out mills 5s
	 */
	private static int TIMEOUTMILLS = 1000 * 5;

	/**
	 * 
	 * @param url
	 * @param formparams
	 * @param failListener
	 * @return
	 */
	public static JSONObject post(String url, List<NameValuePair> formparams) {
		Log.i("", "host : " + url);
		for (NameValuePair n : formparams) {
			Log.i("", n.getName() + " : " + n.getValue());
		}

		JSONObject jsonObject = null;

		HttpPost httpPost = new HttpPost(url);

		HttpClient httpClient = new DefaultHttpClient();

		httpClient.getParams().setParameter(
				CoreConnectionPNames.CONNECTION_TIMEOUT, TIMEOUTMILLS);

		httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
				TIMEOUTMILLS);

		HttpResponse response = null;

		try {
			Log.e("formparams", formparams.toString());

			httpPost.setEntity(new UrlEncodedFormEntity(formparams, HTTP.UTF_8));

			response = httpClient.execute(httpPost);

		} catch (HttpHostConnectException hhce) {
			jsonObject = new JSONObject();
			try {
				jsonObject.put(General.STATUS, -40);
				jsonObject.put(General.MESSAGE, "未链接到服务器，请检查网络是否链接");
			} catch (Exception e13) {
				hhce.printStackTrace();
			}
			return jsonObject;
		} catch (ConnectTimeoutException cte) {
			jsonObject = new JSONObject();
			try {
				jsonObject.put(General.STATUS, -40);
				jsonObject.put(General.MESSAGE, "链接超时，请先检查网络是否链接");
			} catch (Exception e13) {
				cte.printStackTrace();
			}
			return jsonObject;
		} catch (UnknownHostException e) {
			jsonObject = new JSONObject();
			try {
				jsonObject.put(General.STATUS, -1);
				jsonObject.put(General.MESSAGE, "未找到服务器，请先检查网络是否链接");
			} catch (Exception e13) {
				e.printStackTrace();
			}
			return jsonObject;
		} catch (UnsupportedEncodingException uee) {
			jsonObject = new JSONObject();
			try {
				jsonObject.put(General.STATUS, -11);
				jsonObject.put(General.MESSAGE, "字符编码错误");
			} catch (Exception e13) {
				e13.printStackTrace();
			}
			return jsonObject;
		} catch (ClientProtocolException cpe) {
			jsonObject = new JSONObject();
			try {
				jsonObject.put(General.STATUS, -12);
				jsonObject.put(General.MESSAGE, "http协议错误");
			} catch (Exception e13) {
				e13.printStackTrace();
			}
			return jsonObject;
		} catch (IOException ioe) {
			jsonObject = new JSONObject();
			try {
				jsonObject.put(General.STATUS, -13);
				jsonObject.put(General.MESSAGE, "IO错误");
			} catch (Exception e13) {
				e13.printStackTrace();
			}
			return jsonObject;
		} catch (Exception ioe) {
			jsonObject = new JSONObject();
			try {
				jsonObject.put(General.STATUS, -14);
				jsonObject.put(General.MESSAGE, "未知错误");
			} catch (Exception e13) {
				e13.printStackTrace();
			}
			return jsonObject;
		}

		Log.i(TAG, " response StatusCode :"
				+ response.getStatusLine().getStatusCode());
		if (response == null || 200 != response.getStatusLine().getStatusCode()) {
			jsonObject = new JSONObject();
			try {
				jsonObject.put(General.STATUS, -2);
				jsonObject.put(General.MESSAGE, "请求返回Code："
						+ response.getStatusLine().getStatusCode());
			} catch (Exception e1) {
				e1.printStackTrace();
			}
			return jsonObject;
		}

		HttpEntity httpEntity = response.getEntity();

		try {

			String content = EntityUtils.toString(httpEntity);
			Log.i(TAG, " response Content :" + content);
			jsonObject = new JSONObject(content);

		} catch (JSONException je) {
			je.printStackTrace();

			jsonObject = new JSONObject();
			try {
				jsonObject.put(General.STATUS, -3);
				jsonObject.put(General.MESSAGE, "返回数据格式错误");
			} catch (Exception e1) {
				e1.printStackTrace();
			}
			return jsonObject;
		} catch (ParseException je) {
			je.printStackTrace();

			jsonObject = new JSONObject();
			try {
				jsonObject.put(General.STATUS, -31);
				jsonObject.put(General.MESSAGE, "数据转换");
			} catch (Exception e1) {
				e1.printStackTrace();
			}
			return jsonObject;
		} catch (IOException ioe) {
			ioe.printStackTrace();

			jsonObject = new JSONObject();
			try {
				jsonObject.put(General.STATUS, -13);
				jsonObject.put(General.MESSAGE, "IO错误");
			} catch (Exception e13) {
				e13.printStackTrace();
			}
			return jsonObject;
		}

		return jsonObject;
	}

	/**
	 * 未用到
	 * 
	 * @param url
	 * @return
	 */
	protected JSONObject get(String url) {
		Log.i("", "get url : " + url);
		JSONObject jsonObject = null;
		BufferedReader in = null;

		HttpGet httpPost = null;

		httpPost = new HttpGet(url);

		HttpClient httpClient = new DefaultHttpClient();

		httpClient.getParams().setParameter(
				CoreConnectionPNames.CONNECTION_TIMEOUT, TIMEOUTMILLS);

		httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
				TIMEOUTMILLS);

		HttpResponse response = null;

		try {
			response = httpClient.execute(httpPost);
		} catch (ClientProtocolException e1) {
			e1.printStackTrace();
			jsonObject = new JSONObject();
			try {
				jsonObject.put(General.STATUS, -12);
				jsonObject.put(General.MESSAGE, "http协议错误");
			} catch (Exception e11) {
				e1.printStackTrace();
			}
			return jsonObject;
		} catch (UnknownHostException e) {
			e.printStackTrace();
			jsonObject = new JSONObject();
			try {
				jsonObject.put(General.STATUS, -1);
				jsonObject.put(General.MESSAGE, "未找到服务器，请先检查网络是否链接");
			} catch (Exception e13) {
				e.printStackTrace();
			}
			return jsonObject;
		} catch (IOException e1) {
			e1.printStackTrace();
			jsonObject = new JSONObject();
			try {
				jsonObject.put(General.STATUS, -13);
				jsonObject.put(General.MESSAGE, "IO错误");
			} catch (Exception e13) {
				e13.printStackTrace();
			}
			return jsonObject;
		}

		if (response == null) {
			jsonObject = new JSONObject();
			try {
				jsonObject.put(General.STATUS, -1);
				jsonObject.put(General.MESSAGE, "未知错误");
			} catch (Exception e1) {
				e1.printStackTrace();
			}
			return jsonObject;
		} else if (response.getStatusLine() == null) {
			jsonObject = new JSONObject();
			try {
				jsonObject.put(General.STATUS, -1);
				jsonObject.put(General.MESSAGE, "未知错误");
			} catch (Exception e1) {
				e1.printStackTrace();
			}
			return jsonObject;
		} else if (response.getStatusLine().getStatusCode() != 200) {
			Log.i("", TAG + " response StatusCode :"
					+ response.getStatusLine().getStatusCode());
			jsonObject = new JSONObject();
			try {
				jsonObject.put(General.STATUS, -2);
				jsonObject.put(General.MESSAGE, "请求返回Code："
						+ response.getStatusLine().getStatusCode());
			} catch (Exception e1) {
				e1.printStackTrace();
			}
			return jsonObject;
		}

		try {
			in = new BufferedReader(new InputStreamReader(response.getEntity()
					.getContent()));
		} catch (IllegalStateException e1) {
			jsonObject = new JSONObject();
			try {
				jsonObject.put(General.STATUS, -13);
				jsonObject.put(General.MESSAGE, "非法状态错误");
			} catch (Exception e13) {
				e13.printStackTrace();
			}
			return jsonObject;
		} catch (IOException e1) {
			jsonObject = new JSONObject();
			try {
				jsonObject.put(General.STATUS, -13);
				jsonObject.put(General.MESSAGE, "IO错误");
			} catch (Exception e13) {
				e13.printStackTrace();
			}
			return jsonObject;
		}
		StringBuffer sb = new StringBuffer("");
		String line = "";
		String NL = System.getProperty("line.separator");
		try {
			while ((line = in.readLine()) != null) {
				sb.append(line + NL);
			}

			try {
				Log.d("", "get返回数据：" + sb.toString());
				jsonObject = new JSONObject(sb.toString());
			} catch (Exception e) {
				jsonObject = new JSONObject();
				try {
					jsonObject.put(General.STATUS, -3);
					jsonObject.put(General.MESSAGE, "返回数据格式错误");
				} catch (Exception e1) {
					e1.printStackTrace();
				}
				return jsonObject;
			}

		} catch (IOException e) {
			jsonObject = new JSONObject();
			try {
				jsonObject.put(General.STATUS, -13);
				jsonObject.put(General.MESSAGE, "IO错误");
			} catch (Exception e13) {
				e13.printStackTrace();
			}
			return jsonObject;
		} finally {
			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return jsonObject;
	}
}
